package com.usernet.product.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.usernet.product.comm.BaseAction;
import com.usernet.product.entity.Admin;
import com.usernet.product.entity.Photo;
import com.usernet.product.entity.Software;
import com.usernet.product.tools.FileTools;
import com.usernet.product.utils.DateUtils;
import com.usernet.product.utils.LogConstants;
import com.usernet.product.utils.ProductConfig;
import com.usernet.product.utils.ProductUtils;

public class PhotoAction extends BaseAction {

	/**
	 * 删除截图
	 * 
	 * @throws IOException
	 */
	public ActionForward doDelete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			Photo photo = (Photo) photoDao.getById(Photo.class, id);
			if (photoDao.delete(photo)) {
				String photoPath = ProductConfig.realPath + "\\upload\\photo\\"
						+ photo.getPhoto();
				File file = new File(photoPath);
				if (file.exists()) {
					file.delete();
				}
				Admin admin = (Admin) request.getSession()
						.getAttribute("admin");
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(), String
						.format(LogConstants.delete_photo, new Object[] { 1 }),
						null);
				response.getWriter().write("1");
			} else {
				response.getWriter().write("0");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			response.getWriter().write("0");
		}
		response.getWriter().flush();
		return null;
	}

	/** 锁定截图 */
	public ActionForward doCancle(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			Photo photo = (Photo) photoDao.getById(Photo.class, id);
			photo.setStatus(1);
			if (photoDao.modify(photo)) {
				Admin admin = (Admin) request.getSession()
						.getAttribute("admin");
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(), String
						.format(LogConstants.lock_photo, new Object[] { 1 }),
						null);
				response.getWriter().write("1");
			} else {
				response.getWriter().write("0");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			response.getWriter().write("0");
		}
		return null;
	}

	/** 解锁截图 */
	public ActionForward doOK(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			Photo photo = (Photo) photoDao.getById(Photo.class, id);
			photo.setStatus(0);
			if (photoDao.modify(photo)) {
				Admin admin = (Admin) request.getSession()
						.getAttribute("admin");
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(), String
						.format(LogConstants.unlock_photo, new Object[] { 1 }),
						null);
				response.getWriter().write("1");
			} else {
				response.getWriter().write("0");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			response.getWriter().write("0");
		}
		response.getWriter().flush();
		return null;
	}

	/** 添加截图 */
	public ActionForward doAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int softId = Integer.parseInt(request.getParameter("softId"));
		Hashtable<?, ?> files = form.getMultipartRequestHandler()
				.getFileElements();
		int count = 0;
		if (files != null & files.size() > 0) {
			Enumeration<?> enums = files.keys();
			String fileKey = null;
			int i = 0;
			String filePath = ProductConfig.realPath + "upload\\photo\\"
					+ DateUtils.getDate() + "\\";
			FileTools.createDateFile(filePath);
			while (enums.hasMoreElements()) {
				// 取得key
				fileKey = (String) (enums.nextElement());
				// 初始化每一个FormFile(接口)
				FormFile file = (FormFile) files.get(fileKey);
				// 分别上传
				String name = file.getFileName();
				if (name != null && !"".equals(name.trim())) {
					String fileType = name.substring(name.lastIndexOf("."),
							name.length());
					if (!".png".equals(fileType.toLowerCase())
							&& !".jpg".equals(fileType.toLowerCase())) {
						request.setAttribute("msg", "已经添加成功了" + count
								+ "张,图片类型错误,必须为PNG或JPG");
						request.setAttribute("return",
								"/admin/page/software_add_3.jsp&id=" + softId);
						return mapping.findForward("admin_msg");
					} else {
						String photpName = UUID.randomUUID().toString();

						InputStream in = file.getInputStream();

						OutputStream out = new FileOutputStream(filePath
								+ photpName);
						out.write(file.getFileData(), 0, file.getFileSize());
						in.close();
						in = null;
						out.close();
						out = null;
						Photo photo = new Photo();
						photo.setPhoto(DateUtils.getDate() + "/" + photpName);
						photo.setStatus(0);// 可用
						Software soft = new Software();
						soft.setId(softId);
						photo.setSoftware(soft);
						photo
								.setTime(new Timestamp(System
										.currentTimeMillis()));
						int photoId = photoDao.save(photo);
						if (photoId > 0) {
							count++;
						} else {
							request.setAttribute("msg", "添加失败,(已经添加成功了" + count
									+ "张)");
							request.setAttribute("return",
									"software.do?method=toList");
							return mapping.findForward("admin_msg");
						}
					}
				}
				i++;
			}

		}
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		// 添加日志
		ProductUtils.addAdminLog(request, admin.getLoginName(), String.format(
				LogConstants.add_photo, new Object[] { files.size() }), null);
		return mapping.findForward("other");
	}

}
